import {AfterViewInit, Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Message} from '../../../../../ng-tools/src/message/message';
import {Subscription, timer} from 'rxjs';
import {DvbConfigService} from '../../../../services/api/dvb-config.service';
import {LoadingComponent, MessageService, ProgressBarService} from '../../../../../ng-tools';
import {FormBuilder, FormGroup} from '@angular/forms';
import {st} from '@angular/core/src/render3';

@Component({
  selector: 'network-manage',
  templateUrl: './network-manage.component.html',
  styleUrls: ['./network-manage.component.scss']
})
export class NetworkManageComponent implements OnInit, AfterViewInit, OnDestroy, Message {
  @ViewChild(LoadingComponent) loading: LoadingComponent;
  subscriptions: Subscription;
  networkInfo;
  currentType;
  currentMold = 2;
  currentStatus = 1;
  currentNetworkInfo;
  networkForm: FormGroup;
  defaultFormValue;
  loadingOptions = {
    id: 'networkStatusModal',
    message: '',
    textColor: 'teal'
  };
  breadcrumb = [
    {name: '网络管理', cssIcon: 'fa fa-fw fa-cubes'},
    {name: '网络配置', cssIcon: 'fa fa-fw fa-file'}
  ];

  constructor(private dvbConfigService: DvbConfigService,
              private message: MessageService,
              private formBuilder: FormBuilder,
              public progress: ProgressBarService) {
    this.networkForm = this.formBuilder.group({
      addr: [''],
      netmask: [''],
      gateway: [''],
      dns: ['']
    });
    this.defaultFormValue = {
      addr: '',
      netmask: '',
      gateway: '',
      dns: ''
    };
    this.networkForm.patchValue(this.defaultFormValue);
  }

  ngOnInit() {
    this.dvbConfigService.get(this.dvbConfigService.urls.getNetworkInfo).subscribe((resp) => {
      this.networkInfo = resp.body;
      console.log(this.networkInfo);
      this.message.sendMessage('page load progress', this);
    });
  }

  changeCurrentType(type: number) {
    this.currentType = type;
    this.currentNetworkInfo = this.networkInfo[this.currentType];
    const info = this.currentNetworkInfo.info;
    if (info !== null) {
      this.networkForm.patchValue({
        addr: info.addr,
        netmask: info.netmask,
        gateway: info.gateway,
        dns: info.dns
      });
    } else {
      this.networkForm.patchValue({
        addr: '',
        netmask: '',
        gateway: '',
        dns: ''
      });
    }
  }

  changeNetworkStauts(status: number) {
    if (this.currentType !== undefined) {
      if (status === 1) {
        this.loading.show('正在启动该网卡...');
        this.dvbConfigService.post(this.dvbConfigService.urls.change_network_status, {'interface': this.currentNetworkInfo.name, 'status': status}).subscribe((resp) => {
          this.loading.show('网卡启动成功!');
          timer(1000).subscribe(() => {
            this.loading.hide();
            this.dvbConfigService.get(this.dvbConfigService.urls.getNetworkInfo).subscribe((resp1) => {
              this.networkInfo = resp1.body;
            });
          });
        });
      } else {
        this.loading.show('正在禁用该网卡...');
        this.dvbConfigService.post(this.dvbConfigService.urls.change_network_status, {'interface': this.currentNetworkInfo.name, 'status': status}).subscribe((resp) => {
          this.loading.show('网卡禁用成功!');
          timer(1000).subscribe(() => {
            this.loading.hide();
            this.dvbConfigService.get(this.dvbConfigService.urls.getNetworkInfo).subscribe((resp1) => {
              this.networkInfo = resp1.body;
            });
          });
        });
      }
    }
  }

  changeCurrentMold(mold: number) {
    this.currentMold = mold;
  }

  setNetworkInfo() {
    if (this.currentType !== undefined) {
      if (this.currentMold === 1 && this.currentStatus === 1) {
        console.log({'connection_type': this.currentMold, 'interface': this.currentNetworkInfo.name});
        this.dvbConfigService.post(this.dvbConfigService.urls.change_network_info,
          {'connection_type': this.currentMold, 'interface': this.currentNetworkInfo.name}).subscribe(() => {
          this.dvbConfigService.get(this.dvbConfigService.urls.getNetworkInfo).subscribe((resp) => {
            this.networkInfo = resp.body;
            // {'name': 'wlp5s0', 'info': {addr: "192.168.1.3", broadcast: "192.168.1.255", gateway: "192.168.1.1", netmask: "255.255.255.0"}}
            for (const info of this.networkInfo) {
              if (info.name === this.currentNetworkInfo.name) {
                const newNetworkInfo = {
                  addr: info.info.addr,
                  netmask: info.info.netmask,
                  gateway: info.info.gateway,
                  dns: info.info.dns
                };
                this.networkForm.patchValue(newNetworkInfo);
              }
            }
          });
        });
      } else {
        if (this.networkForm.valid) {
          console.log({'connection_type': this.currentMold, 'interface': this.currentNetworkInfo.name, 'data': this.networkForm.value});
          this.dvbConfigService.post(this.dvbConfigService.urls.change_network_info,
            {'connection_type': this.currentMold, 'interface': this.currentNetworkInfo.name, 'data': this.networkForm.value}).subscribe((resp) => {
            this.dvbConfigService.get(this.dvbConfigService.urls.getNetworkInfo).subscribe((resp) => {
              this.networkInfo = resp.body;
              // {'name': 'wlp5s0', 'info': {addr: "192.168.1.3", broadcast: "192.168.1.255", gateway: "192.168.1.1", netmask: "255.255.255.0"}}
              for (const info of this.networkInfo) {
                if (info.name === this.currentNetworkInfo.name) {
                  const newNetworkInfo = {
                    addr: info.info.addr,
                    netmask: info.info.netmask,
                    gateway: info.info.gateway,
                    dns: info.info.dns
                  };
                  this.networkForm.patchValue(newNetworkInfo);
                }
              }
            });
          });
        }
      }
    }
  }

  ngAfterViewInit(): void {
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
  }

  ngOnDestroy(): void {
  }

}

// {'name': 'wlp5s0', 'info': {addr: "192.168.1.3", broadcast: "192.168.1.255", gateway: "192.168.1.1", netmask: "255.255.255.0"}}
